//
//  AppDelegate.m
//  GC_OC
//
//  Created by 曾 on 2022/1/16.
//


#import "AppDelegate.h"
#import "ViewController.h"
#import "CategoryView.h"
#import "FKLoginTool.h"


#import <JPUSHService.h>
// iOS10 注册 APNs 所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
// 引入JAnalytics功能所需头文件
#import "JANALYTICSService.h"



@interface AppDelegate ()<JPUSHRegisterDelegate>

@end

@implementation AppDelegate
+ (AppDelegate *)delegate {
    return [UIApplication sharedApplication].delegate;
}
- (void)configNowPlayingCenter {
    NSMutableDictionary * info = [NSMutableDictionary dictionary];
    info[MPMediaItemPropertyTitle] = _player.currentSong[@"name"];
    info[MPMediaItemPropertyArtist] = _player.currentSong[@"teacher_name"];
    info[MPMediaItemPropertyGenre] = _player.currentSong[@"media_class_name"];
    
//    [info setObject:_player.currentSong[@"name"] forKey:MPMediaItemPropertyTitle];
//    [info setObject:_player.currentSong[@"teacher_name"] forKey:MPMediaItemPropertyArtist];
//    [info setObject:_player.currentSong[@"media_class_name"] forKey:MPMediaItemPropertyGenre];
    
    [info setObject:@(self.player.playTime.intValue) forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];
    [info setObject:@(1) forKey:MPNowPlayingInfoPropertyPlaybackRate];
    [info setObject:@(self.player.playDuration.intValue) forKey:MPMediaItemPropertyPlaybackDuration];
    [[MPNowPlayingInfoCenter defaultCenter]setNowPlayingInfo:info];
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    self.objectAFNet=[[ObjectAFNetWorking alloc]init];
    
    // 获取公钥
    [self.objectAFNet getUrlStr:[NSString stringWithFormat:@"%@/api/home/getToken",server_addr] finish:^(id  _Nonnull dataString) {
        NSDictionary* dic=[NSJSONSerialization JSONObjectWithData:dataString options:NSJSONReadingMutableContainers error:nil];
        NSString *code = [NSString stringWithFormat:@"%@", dic[@"code"]];
        if (dic[@"data"][@"public_key"] && [code isEqualToString:@"1"]) {
            [MBGeneralManager manager].publicKey = dic[@"data"][@"public_key"];
        } else {
            [MBGeneralManager manager].publicKey = @"";
        }
    } andError:^(NSError * _Nonnull error) {
        [MBGeneralManager manager].publicKey = @"";
    }];
    
    
    
    //打开音频会话
    AVAudioSession * session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    [session setActive:YES error:nil];
    self.player = [SUPlayerManager manager];
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

    
    NSInteger palyTimeType=[[NSUserDefaults standardUserDefaults] integerForKey:@"palyTimeType"];
    if(palyTimeType<0)
    {
        [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"palyTimeType"];
    }
    if (@available(iOS 15.0, *)) {
        [UITableView appearance].sectionHeaderTopPadding = 0;
    }
//    [UIApplication sharedApplication].statusBarHidden = NO;
//    if (@available(iOS 13.0, *)) {
//        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
//    } else {
//        // Fallback on earlier versions
//    }
    
    //网络状态监听
    self.reachabilityManager = [AFNetworkReachabilityManager sharedManager];
    [self.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
                    case AFNetworkReachabilityStatusUnknown:
                        NSLog(@"未识别的网络");
                        break;

                    case AFNetworkReachabilityStatusNotReachable:
                        NSLog(@"不可达的网络(未连接)");
                        break;

                    case AFNetworkReachabilityStatusReachableViaWWAN:
                        NSLog(@"2G,3G,4G...的网络");
                        break;

                    case AFNetworkReachabilityStatusReachableViaWiFi:
                        NSLog(@"wifi的网络");
                        break;
                    default:
                        break;
                }
    }];
    [self.reachabilityManager startMonitoring];

    
    // 获取线上最新的APP的版本号
    [FKLoginTool checkAppVersion];
    // 注册极光
    [self registApNs:launchOptions];
//    [FKCacheTool clearRequestData];
    

    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
    [SVProgressHUD setMaximumDismissTimeInterval:2.0];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate:) name:UIApplicationWillTerminateNotification object:nil];

    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    NSError *error;
    BOOL success = [audioSession setCategory:AVAudioSessionCategoryPlayback error:&error];
    if (!success) {
        NSLog(@"Error setting category: %@", error.localizedDescription);
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterruption:) name:AVAudioSessionInterruptionNotification object:nil];
    
    return YES;
}

- (void)handleInterruption:(NSNotification *)notification {
    AVAudioSessionInterruptionType type = [notification.userInfo[AVAudioSessionInterruptionTypeKey] integerValue];
    if (type == AVAudioSessionInterruptionTypeBegan) {
        // Audio has been interrupted, pause playback
        NSLog(@"Audio has been interrupted");
        if (self.player.currentSong) {
            [self.player pausePlay];
        }
    } else if (type == AVAudioSessionInterruptionTypeEnded) {
        AVAudioSessionInterruptionOptions options = [notification.userInfo[AVAudioSessionInterruptionOptionKey] integerValue];
        if (options == AVAudioSessionInterruptionOptionShouldResume) {
            // Audio has resumed, resume playback
            NSLog(@"Audio has resumed");
        }
    }
}

#pragma mark - 极光推送注册
-(void)registApNs:(NSDictionary *)launchOptions
{
    JPUSHRegisterEntity *entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    [JPUSHService setupWithOption:launchOptions appKey:AppKey_JPush channel:@"App Store" apsForProduction:YES advertisingIdentifier:nil];
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0){
            FKLog(@"registrationID获取成功：%@",registrationID);
            //            [FKCacheTool saveRegistrationID:registrationID];
        } else{
            FKLog(@"registrationID获取失败，code：%d",resCode);
        }
    }];
    
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(didReceiveJPushMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
    
    // 添加极光闪退日志分析
    JANALYTICSLaunchConfig * config = [[JANALYTICSLaunchConfig alloc] init];
    config.appKey = AppKey_JPush;
    config.channel = @"App Store";
    [JANALYTICSService setupWithConfig:config];
    [JANALYTICSService crashLogON];
}

- (void)didReceiveJPushMessage:(NSNotification *)notification {
//    NSDictionary * userInfo = [notification userInfo];
    //    NSDictionary *extras = [userInfo valueForKey:@"extras"];
    
}

//注册 APNs 成功并上报 DeviceToken
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
//    NSString *deviceTokenStr = [[deviceToken base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength] fk_md5String];
//    [FKCacheTool saveDeviceToken:deviceTokenStr];
    [JPUSHService registerDeviceToken:deviceToken];
}
//实现注册 APNs 失败接口（可选）
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    FKLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    // Required, For systems with less than or equal to iOS 6
    [JPUSHService handleRemoteNotification:userInfo];
}

#ifdef __IPHONE_12_0
// iOS 12 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification API_AVAILABLE(ios(10.0)){
    if (notification && [notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //从通知界面直接进入应用
    }else{
        //从通知设置界面进入应用
    }
}
#endif

#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#pragma mark- JPUSHRegisterDelegate
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler  API_AVAILABLE(ios(10.0)){
    UNNotificationContent *content = notification.request.content; // 收到推送的消息内容
    
    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    NSDictionary *userInfo = content.userInfo;
    
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        FKLog(@"iOS10 收到远程通知");
    } else {
        // 判断为本地通知
        FKLog(@"iOS10 前台收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
    }
    // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置
    if ([FKCacheTool isLogin]) { // 有session才收通知
        completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert);
    }
}

- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler  API_AVAILABLE(ios(10.0)){
    UNNotificationContent *content = response.notification.request.content; // 收到推送的消息内容
    
    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    NSDictionary *userInfo = content.userInfo;
    NSString *messageId = userInfo[@"messageId"]; // 消息id，通过这个获取消息详情
    
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        FKLog(@"iOS10 收到远程通知");
        
        NSString *url = userInfo[@"url"];
        if (url && url.length > 0) {
//            FKOAMessageVC *vc = [[FKOAMessageVC alloc] init];
//            vc.url = url;
//            FKNavVC *nav = [[FKNavVC alloc] initWithRootViewController:vc];
//            [[UIApplication sharedApplication].delegate.window.rootViewController fk_presentViewController:nav animated:true completion:nil];
        } else {
//            FKMessageDetailVC *vc = [[FKMessageDetailVC alloc] init];
//            vc.messageId = messageId;
//            vc.showBack = true;
//            FKNavVC *nav = [[FKNavVC alloc] initWithRootViewController:vc];
//            [[UIApplication sharedApplication].delegate.window.rootViewController fk_presentViewController:nav animated:true completion:nil];
        }
    } else {
        // 判断为本地通知
        FKLog(@"iOS10 收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
        
        NSString *type = userInfo[@"type"];
        if ([type isEqualToString:@"RemoteVideoConnection"]) {
//            NSDictionary *data = userInfo[@"data"];
//            UIWindow *window = [UIApplication sharedApplication].delegate.window;
//            FKVideoConnectVC *vc = [[FKVideoConnectVC alloc] init];
//            vc.remoteInvitation = [FKInviteInfo mj_objectWithKeyValues:data];
//            [window.rootViewController fk_presentViewController:vc animated:true completion:nil];
        }
    }
    
    if ([FKCacheTool isLogin]) {
        completionHandler();  // 系统要求执行这个方法
    }
}

// 监测通知授权状态返回的结果
- (void)jpushNotificationAuthorization:(JPAuthorizationStatus)status withInfo:(NSDictionary *)info {
    
}

#endif

- (void)applicationWillResignActive:(UIApplication *)application {
    
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // 设置允许后台播放
//    AVAudioSession*session=[AVAudioSession sharedInstance];
//    [session setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:nil];
//    [session setActive:YES error:nil];
    
//    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
     
    // 实现如下代码，才能使程序处于后台时被杀死，调用applicationWillTerminate:方法
    [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^(){}];
    
    [self.reachabilityManager stopMonitoring];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
//    [application setApplicationIconBadgeNumber:0];
//    [application cancelAllLocalNotifications];
    
    
    [self.reachabilityManager startMonitoring];
}

- (void)applicationDidBecomeActive:(UIApplication *)application{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    
    // 检验内容版本
    [FKLoginTool checkContentVersion];
}


- (void)applicationWillTerminate:(UIApplication *)application {
    
    if (self.player.currentSong && self.player.playDuration.floatValue>0 && self.player.progress>0 && self.player.playTime) {
        // 保存当前播放歌曲，下次启动用
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSArray *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *path = [documentPath firstObject];
        NSString *plistPath = [path stringByAppendingPathComponent:@"savedSong.plist"];
        BOOL isFile = [fileManager fileExistsAtPath:plistPath];
        if (isFile) {
            [fileManager removeItemAtPath:plistPath error:nil];
        }
        NSDictionary *dic = @{@"index":@(self.player.currentSongIndex),
                              @"arr":self.player.songList,
                              @"playtime":self.player.playTime,
                              @"playdura":self.player.playDuration,
                              @"progress":@(self.player.progress),
                              @"rate":@(self.player.saveRate)
        };
        NSData *dicData = [NSKeyedArchiver archivedDataWithRootObject:dic];
        [dicData writeToFile:plistPath atomically:YES];
        
        [[NSUserDefaults standardUserDefaults] setObject:@"YES" forKey:@"isSong"];
    } else {
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"isSong"];
    }
}


#pragma mark - private
///查询APP版本号
- (NSString *)appVersion{
    NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
    NSString* version =[infoDict objectForKey:@"CFBundleShortVersionString"];
    return version;
}

/// 在这里写支持的旋转方向，为了防止横屏方向，应用启动时候界面变为横屏模式
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    // 可以这么写
    if (self.allowOrentitaionRotation) {
        return UIInterfaceOrientationMaskAllButUpsideDown;
    }
    return UIInterfaceOrientationMaskPortrait;
}

+ (instancetype)shared {
    return (AppDelegate *)[UIApplication sharedApplication].delegate;
}

- (void)stopAudioPlay {
    UIButton *bt = [self.toolBarView viewWithTag:3003];
    bt.selected = YES;
    [self.audioPlayer stop];
}
- (void)pauseAudioPlay {
    [self.audioPlayer pause];
}
- (void)playAudio {
    [self.audioPlayer play];
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
    UIButton *playButton = (UIButton *)[self.toolBarView viewWithTag:3003];
    playButton.selected = YES;
    
    if (self.audioPlayFinish != nil ) {
        self.audioPlayFinish();
    }
}



- (void)playAudioSound:(NSString *) url {
    
//    url = @"http://chiatsolar.com/%E9%9F%B3%E9%A2%91/%E4%B8%93%E9%A2%98/%E6%9C%B1%E7%89%A7%E5%B8%88%E8%AE%B2%E9%81%93/%E3%80%90%E7%BB%8F%E5%85%B8%E3%80%91/1688.%E3%80%90%E7%BB%8F%E5%85%B8%E3%80%91%E8%80%B6%E7%A8%A3%E7%9A%84%E5%8D%81%E5%AD%97%E6%9E%B6.mp3";
        
    
    NSString *encodedString = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)url,
                                                              (CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",
                                                              NULL,
                                                              kCFStringEncodingUTF8));
    NSLog(@"%@",encodedString);
    NSURL *soundURL = [NSURL URLWithString:encodedString];
    if (self.audioPlayer) {
//        if (self.audioPlayer.playing) {
//            if (self.audioPlayFinish != nil ) {
//                self.audioPlayFinish();
//            }
//        }
    }
    
    self.audioPlayer = nil;
    NSData *data = [[NSData alloc] initWithContentsOfURL:soundURL];
    self.audioPlayer = [[AVAudioPlayer alloc] initWithData:data error:nil];
    self.audioPlayer.delegate = self;
    [self.audioPlayer play];
    dispatch_async(dispatch_get_main_queue(), ^{
        UIButton *bt = (UIButton *)[self.toolBarView viewWithTag:3003];
        bt.selected = NO;
    });
}

- (UIView *)toolBarView {
    if (!_toolBarView) {
        CAGradientLayer *gradient = [CAGradientLayer layer];
        gradient.startPoint = CGPointMake(0, 0);
        gradient.endPoint = CGPointMake(0, 1);
        gradient.frame =CGRectMake(0,0,SCREEN_WIDTH,50);
        gradient.colors = [NSArray arrayWithObjects:(id)XHUIColorFromRGB(0xF4F4F4).CGColor,(id)XHUIColorFromRGB(0xFDFDFD).CGColor,nil];
        
        _toolBarView = [UIView new];
        _toolBarView.tag = 7000;
//        _toolBarView.hidden = YES;
//        _toolBarView.backgroundColor = [UIColor redColor];
        [_toolBarView.layer insertSublayer:gradient atIndex:0];
        
        UILabel *tLabel = [UILabel new];
        tLabel.tag = 3001;
        tLabel.textColor = [UIColor blackColor];
        tLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightRegular];
        [_toolBarView addSubview:tLabel];
        
        UILabel *f_sLabel = [UILabel new];
        f_sLabel.tag = 3002;
        f_sLabel.textColor = XHUIColorFromRGB(0x666666);
        f_sLabel.font = [UIFont systemFontOfSize:12 weight:UIFontWeightRegular];
        [_toolBarView addSubview:f_sLabel];
        
        UIButton *playButton = [UIButton new];
        playButton.tag = 3003;
        [playButton setImage:[UIImage imageNamed:@"narrow_playBtn_play"] forState:UIControlStateNormal];
        [playButton setImage:[UIImage imageNamed:@"icon_zimu_defaults"] forState:UIControlStateSelected];
        [playButton addTarget:self action:@selector(playAudioAction:) forControlEvents:UIControlEventTouchUpInside];
        [_toolBarView addSubview:playButton];
        
        UIButton *categoryButton = [UIButton new];
        [categoryButton setImage:[UIImage imageNamed:@"24gf-playlistMusic"] forState:UIControlStateNormal];
        [categoryButton addTarget:self action:@selector(categoryAction) forControlEvents:UIControlEventTouchUpInside];
        [_toolBarView addSubview:categoryButton];
        
        UIView *barLineView = [UIView new];
        barLineView.backgroundColor = XHUIColorFromRGB(0xE5E5E5);
        [_toolBarView addSubview:barLineView];
        
        [barLineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(0.5);
            make.left.right.top.mas_equalTo(0);
        }];
        
        [tLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(16);
            make.left.equalTo(_toolBarView).offset(14);
            make.top.equalTo(_toolBarView).offset(7);
            make.width.greaterThanOrEqualTo(@200);
            
        }];
        [f_sLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(14);
            make.left.equalTo(_toolBarView).offset(14);
            make.top.equalTo(tLabel.mas_bottom).offset(5);
            make.width.greaterThanOrEqualTo(@200);
        }];
        [categoryButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(27);
            make.right.equalTo(_toolBarView).offset(-17);
            make.centerY.equalTo(_toolBarView).offset(0);
            make.width.mas_equalTo(19);
        }];
        [playButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(32);
            make.right.equalTo(categoryButton.mas_left).offset(-23);
            make.centerY.equalTo(_toolBarView).offset(0);
            make.width.mas_equalTo(32);
        }];
    }
    return _toolBarView;
}

- (void)refreshToolBarTitle:(LinkerModel *)fObj sObj:(LinkerModel *)sObj tObj:(LinkerModel *)tObj {
    UILabel *tLabel = (UILabel *)[self.toolBarView viewWithTag:3001];
    UILabel *f_sLabel = (UILabel *)[self.toolBarView viewWithTag:3002];

    if (tObj.name.length != 0) {
        tLabel.text = tObj.name;

    }
    
    if (fObj.name.length != 0 && sObj.name.length != 0) {
        f_sLabel.text = [NSString stringWithFormat:@"%@-%@",fObj.name, sObj.name];

    }
}

- (void)playAudioAction:(UIButton *) sender {
    [sender setSelected:!sender.selected];
    
    if (sender.selected) {
        //暂停
        [[AppDelegate shared] pauseAudioPlay];
    } else {
        //播放
        [[AppDelegate shared] playAudio];
        if (self.audioPlayPause != nil) {
            self.audioPlayPause();
        }
    }
}

- (void)categoryAction {
    CategoryView *view = [CategoryView new];
    view.tag = 5000;
    [view showIn:self.window];

    view.dataSource = self.dataSource;
    [view.tableView reloadData];

    __weak typeof(self) ws = self;

    view.tapCategoryBlock = ^(LinkerModel * _Nonnull obj, CategoryView *view) {
        LinkerModel *fModel;
        LinkerModel *sModel;

        for (LinkerModel *fobj in ws.dataSource) {
            for (LinkerModel *sobj in fobj.list) {
                for (LinkerModel *tobj in sobj.list) {
                    if (tobj == obj) {
                        fModel = fobj;
                        sModel = sobj;
                        break;
                    }
                }
            }
        }
        
        [ws refreshToolBarTitle:fModel sObj:sModel tObj:obj];
        
        
        if (ws.convertCategoryBlock != nil) {
            ws.convertCategoryBlock(obj);
        }
        [view.tableView reloadData];

        
        [self.window showHUD];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self playAudioSound:obj.url];

            [self.window hideBusyHUD];
        });
        
    };
}

- (BOOL)isPlaying {
    return self.audioPlayer.playing;
}


- (void)remoteControlReceivedWithEvent:(UIEvent *)event {
    
    switch (event.subtype)
    {
        case UIEventSubtypeRemoteControlPlay:
            [self.player startPlay];

            break;
        case UIEventSubtypeRemoteControlPause:
            [self.player pausePlay];

            break;
        case UIEventSubtypeRemoteControlNextTrack:
//            [self.playView skipSong:nil];

            break;
        case UIEventSubtypeRemoteControlTogglePlayPause:
            self.player.isPlaying ? [self.player pausePlay] : [self.player startPlay];

            break;
        default:
            break;
    }
}
@end
